package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	"gitee.com/cheng470/openai/ctrl"
	"gitee.com/cheng470/openai/service"
	"gopkg.in/yaml.v3"
)

func main() {
	// load config file
	buf, err := ioutil.ReadFile("resource/app.yml")
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	m := make(map[interface{}]interface{})
	err = yaml.Unmarshal([]byte(buf), &m)
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	host := fmt.Sprint(m["host"])
	port := fmt.Sprint(m["port"])
	api := m["tx_api"].(map[string]interface{})
	secret_id := fmt.Sprint(api["secret_id"])
	secret_key := fmt.Sprint(api["secret_key"])

	chatConfig := m["chat"].(map[string]interface{})
	token := fmt.Sprint(chatConfig["token"])

	fileService := service.NewFileService()
	txAsrService := service.NewTxAsrService(host, port, secret_id, secret_key)
	txTtsService := service.NewTxTtsService(secret_id, secret_key)
	chatService := service.NewChatService(token)

	controller := ctrl.NewController(*fileService, *txAsrService, *txTtsService, *chatService)

	http.HandleFunc("/chat", controller.Chat)
	http.HandleFunc("/audio2text", controller.Audio2text)
	http.HandleFunc("/text2audio", controller.Text2audio)
	http.HandleFunc("/download", controller.HandleDownload)

	controller2 := ctrl.NewController2(*fileService, *txAsrService, *txTtsService, *chatService)
	http.HandleFunc("/v2/chat", controller2.Chat)
	http.HandleFunc("/v2/audio2text", controller2.Audio2text)
	http.HandleFunc("/v2/text2audio", controller2.Text2audio)

	log.Println("server start at http://" + host + ":" + port)
	err = http.ListenAndServe(":"+port, nil)
	if err != nil {
		_, _ = fmt.Fprint(os.Stderr, "ListenAndServe: "+err.Error())
		return
	}
}
